<template>
  <div class="permission-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="权限名称">
          <el-input v-model="formInline.permissionName" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
          <el-button type="success" @click="dialogFormVisible = true" :icon="Plus">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-header">
        <h3 class="table-title">权限列表</h3>
      </div>
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        row-key="id"
        stripe
        highlight-current-row>
        <el-table-column prop="id" type="index" label="权限编号" width="100" align="center" />
        <el-table-column prop="permissionName" label="权限名称" align="center" />
        <el-table-column prop="permissionUrl" label="权限URL" align="center" />
        <el-table-column prop="sort" label="权限序号" width="100" align="center" />
        
        <!-- 添加状态列 -->
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.state"
              :active-value="true"
              :inactive-value="false"
              :active-text="'启用'"
              :inactive-text="'禁用'"
              @change="handleStateChange(scope.row)"
              :before-change="() => beforeStateChange(scope.row)"
            />
          </template>
        </el-table-column>
       
        <el-table-column label="操作" width="150" align="center">
          <template v-slot="scope">
            <el-button type="primary" size="small" :icon="Edit" circle @click="find(scope.row)" />
            <el-button type="danger" size="small" :icon="Delete" circle @click="handleDelete(scope.row)" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="formInline.pageIndex"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[3, 6, 7, 9]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagin.totaleCount"
          background
        />
      </div>
    </el-card>

    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" title="新增权限" width="500" center destroy-on-close>
      <el-form :model="form" :rules="rules" ref="addFormRef" label-position="right" :label-width="formLabelWidth">
        <el-form-item label="权限名称" prop="permissionName" :label-width="formLabelWidth">
          <el-input v-model="form.permissionName" autocomplete="off" placeholder="请输入权限名称" />
        </el-form-item>

        <el-form-item label="权限URL" prop="permissionUrl" :label-width="formLabelWidth">
          <el-input v-model="form.permissionUrl" autocomplete="off" placeholder="请输入权限URL" />
        </el-form-item>

        <el-form-item label="权限序号" prop="sort" :label-width="formLabelWidth">
          <el-input v-model="form.sort" autocomplete="off" placeholder="请输入权限序号" />
        </el-form-item>

        <el-form-item label="父级编号" prop="parentId" :label-width="formLabelWidth">
          <el-input v-model="form.parentId" autocomplete="off" placeholder="请输入父级编号" />
        </el-form-item>

     
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="add()">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="dialogFormVisible2" title="编辑权限" width="500" center destroy-on-close>
      <el-form :model="form2" :rules="rules" ref="editFormRef" label-position="right" :label-width="formLabelWidth">
        <el-form-item label="权限名称" prop="permissionName">
          <el-input v-model="form2.permissionName" autocomplete="off" placeholder="请输入权限名称" />
        </el-form-item>

        <el-form-item label="权限URL" prop="permissionUrl">
          <el-input v-model="form2.permissionUrl" autocomplete="off" placeholder="请输入权限URL" />
        </el-form-item>

        <el-form-item label="权限序号" prop="sort">
          <el-input v-model="form2.sort" autocomplete="off" placeholder="请输入权限序号" />
        </el-form-item>

        <el-form-item label="父级编号" prop="parentId">
          <el-input v-model="form2.parentId" autocomplete="off" placeholder="请输入父级编号" />
        </el-form-item>

       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取消</el-button>
          <el-button type="primary" @click="update()">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="300px" center>
      <div class="delete-dialog-content">
        <el-icon class="delete-icon"><WarningFilled /></el-icon>
        <span>确定要删除该权限吗？</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref, watch, reactive } from 'vue';
import { Search, Plus, Edit, Delete, WarningFilled } from '@element-plus/icons-vue';

import{getPermission,updatePermissionState,addPermission,updatePermission,deletePermission} from'@/HTTPS/server'


onMounted(() => {
  show();
});

const loading = ref(false);
const formInline = reactive({
  permissionName: '',
  pageIndex: 1,
  pageSize: 3,
});

const onSubmit = () => {
  console.log('submit!');
  formInline.pageIndex = 1; // 重置页码
  show();
};

const pagin = ref({
  totaleCount: 0,
  pageCount: 0,
});

watch(formInline, () => {
  show();
}, { deep: true });

const tableData = ref([]);
const show = () => {
  loading.value = true;
  getPermission(formInline )
    .then(res => {
      tableData.value = res.data.data.list;
      pagin.value.pageCount = res.data.data.pageCount;
      pagin.value.totaleCount = res.data.data.totaleCount;
    })
    .catch(error => {
      ElMessage.error('获取权限列表失败');
      console.error(error);
    })
    .finally(() => {
      loading.value = false;
    });
};

// 表单校验规则
const rules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  permissionUrl: [
    { required: true, message: '请输入权限URL', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入权限序号', trigger: 'blur' },
    { type: 'number', message: '序号必须为数字', trigger: 'blur', transform: (val: any) => Number(val) }
  ],
};

// 新增权限
const dialogFormVisible = ref(false);
const formLabelWidth = '100px';
const addFormRef = ref(null);

const form = reactive({
  permissionName: "",
  permissionUrl: "",
  sort: null,
  parentId: null,
});

const add = () => {
  addPermission( form)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message);
        dialogFormVisible.value = false;
        show();
        // 重置表单
        form.permissionName = "";
        form.permissionUrl = "";
        form.sort = null;
        form.parentId = null;
      } else {
        ElMessage.error(res.data.message);
      }
    })
    .catch(error => {
      ElMessage.error('新增权限失败');
      console.error(error);
    });
};

// 编辑权限
const dialogFormVisible2 = ref(false);
const editFormRef = ref(null);

const form2 = reactive({
  id: 0,
  permissionName: "",
  permissionUrl: "",
  sort: null,
  parentId: null,
});

const find = (row: any) => {
  dialogFormVisible2.value = true;
  form2.id = row.id;
  form2.permissionName = row.permissionName;
  form2.permissionUrl = row.permissionUrl;
  form2.sort = row.sort;
  form2.parentId = row.parentId;
};

const update = () => {
  updatePermission(form2)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message);
        dialogFormVisible2.value = false;
        show();
      } else {
        ElMessage.error(res.data.message);
      }
    })
    .catch(error => {
      ElMessage.error('更新权限失败');
      console.error(error);
    });
};

// 删除权限
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref<any>(null);

const handleDelete = (row: any) => {
  deleteDialogVisible.value = true;
  currentDeleteItem.value = row;
};

const confirmDelete = () => {
  if (!currentDeleteItem.value) return;
  
  // 假设有删除API，这里需要根据实际情况修改
  deletePermission( { id: currentDeleteItem.value.id })
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success('删除成功');
        deleteDialogVisible.value = false;
        show();
      } else {
        ElMessage.error(res.data.message || '删除失败');
      }
    })
    .catch(error => {
      ElMessage.error('删除权限失败');
      console.error(error);
    });
};

// 状态修改处理函数
const handleStateChange = (row: any) => {
  const command = {
    id: row.id,
    state: row.state
  };
  
  updatePermissionState(command)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success(res.data.message || '修改状态成功');
      } else {
        ElMessage.error(res.data.message || '修改状态失败');
        // 如果失败，恢复原状态
        row.state = !row.state;
      }
    })
    .catch(error => {
      ElMessage.error('修改权限状态失败');
      console.error(error);
      // 发生错误时恢复原状态
      row.state = !row.state;
    });
};

// 状态修改前确认
const beforeStateChange = (row: any) => {
  return new Promise((resolve) => {
    const newState = !row.state;
    const stateText = newState ? '启用' : '禁用';
    
    // 使用Element Plus提供的确认对话框
    ElMessageBox.confirm(
      `确定要${stateText}权限 "${row.permissionName}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    .then(() => {
      resolve(true); // 用户确认，允许状态改变
    })
    .catch(() => {
      resolve(false); // 用户取消，阻止状态改变
    });
  });
};

</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>

<style scoped>
.permission-container {
  padding: 16px;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  margin-bottom: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  font-size: 18px;
  color: #303133;
  margin: 0;
  font-weight: 500;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.delete-dialog-content {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 16px 0;
}

.delete-icon {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 10px;
}

.icon-preview {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.icon-preview .el-icon {
  font-size: 20px;
  margin-right: 8px;
  color: #409EFF;
}
</style>